package com.example.sam.spinnertest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView tvinfo;
    Spinner spinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        //1.定义数据源
        String[] cities = {"北京","上海","天津","大连"};
        //2.实例化适配器，绑定数据源
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,cities);
        //3.设置Spinner下拉按钮布局
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //4.绑定spinner和adapter
        spinner.setAdapter(adapter);
        spinner.setPrompt("请选择城市");
        //5.spinner条目选择事件
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                tvinfo.setText("您选择的是："+adapterView.getItemAtPosition(i).toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    public void init(){
        spinner = (Spinner)findViewById(R.id.spinner);
        tvinfo = (TextView)findViewById(R.id.textView);
    }
}
